import {Component, ElementRef, OnInit, ViewChild, ViewEncapsulation} from '@angular/core';
import {Observable, timer} from 'rxjs';
import {DetailService} from './detail.service';
import {Authenticate} from '../../core/authenticate.service';
import {ActivatedRoute} from '@angular/router';
import {tap} from 'rxjs/operators';
import {DomSanitizer} from '@angular/platform-browser';

@Component({
  selector: 'app-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class DetailComponent implements OnInit {

  @ViewChild('clipboard') clipboard: ElementRef;
  @ViewChild('pwdContextRef') pwdContextRef: ElementRef;

  goods$: Observable<any>;
  pwdModal = false;
  pwdContext = '';

  goodsRe: any[] = [];
  initLoading = true;

  constructor(public sanitizer: DomSanitizer,
              private auth: Authenticate,
              private service: DetailService,
              private route: ActivatedRoute) {
  }

  ngOnInit() {
    this.route.paramMap.subscribe(params =>
      this.goods$ = this.service.getGoods(this.auth.authenticator.info.openId, params.get('id'))
        .pipe(tap(res => {
          this.pwdContext = this.pwdContext + `【商品】${res.data.title}\n`;
          if (res.data.coupon_remain_count > 0) {
            this.pwdContext = this.pwdContext + `【在售价】${res.data.zk_final_price}元\n`;
            this.pwdContext = this.pwdContext + `【券 额】${res.data.coupon_amount}元 \n`;
            this.pwdContext = this.pwdContext + `【下单价】${Math.round((res.data.zk_final_price - res.data.coupon_amount) * 100) / 100}元 \n`;
          } else {
            this.pwdContext = this.pwdContext + `【在售价】${res.data.reserve_price}元\n`;
            this.pwdContext = this.pwdContext + `【下单价】${res.data.zk_final_price}元 \n`;
          }

          this.pwdContext = this.pwdContext + `【商品领券下单】：长按复制这条信息，去【手掏】可领券并下单${res.pwd}`;
          this.service.goodsRecommend(params.get('id')).subscribe(re => {
            this.goodsRe = re;
            this.initLoading = false;
          });
        })));
  }

  onOpenPwd() {
    this.pwdModal = true;
  }

  onPwdSelect(event: any) {
    event.select();
  }

  copied(event) {
    if (event.isSuccess) {
      this.clipboard.nativeElement.innerHTML = '复制成功';
      this.clipboard.nativeElement.classList.remove('btn-danger');
      this.clipboard.nativeElement.classList.add('btn-success');
    }
    timer(1500).subscribe(() => {
      this.clipboard.nativeElement.innerHTML = '一键复制';
      this.clipboard.nativeElement.classList.remove('btn-success');
      this.clipboard.nativeElement.classList.add('btn-danger');
    });
  }

}
